package com.mk.cloud.common.util;


import com.mk.cloud.common.config.AppConfig;
import com.mk.cloud.common.domain.CpUser;
import org.osgl.$;

import java.math.BigDecimal;
import java.text.DecimalFormat;
import java.util.Map;
import java.util.Objects;
import java.util.Random;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

@SuppressWarnings("unused")
public class S2 {
    /**
     * 选举一个非空字符串
     *
     * @param args
     * @return
     */
    public static String electOneNotBlank(String... args) {
        for (String arg : args) {
            if (org.osgl.util.S.isNotBlank(arg)) return arg;
        }
        return null;
    }

    public static String getUserName(CpUser user) {
//        return S2.electOneNotBlank(user.getRealname(), user.getPhone(), user.getUsername());
        return S2.electOneNotBlank(user.getRealname(), user.getPhone());
    }

    public static String electOneNotNull(String... args) {
        for (String arg : args) {
            if ($.isNull(arg)) continue;
            return arg;
        }
        return null;
    }

    /**
     * 三元替换
     *
     * @param test
     * @param o_true
     * @param o_false
     * @param <T>
     * @return
     */
    public static <T> T three(boolean test, T o_true, T o_false) {
        return test ? o_true : o_false;
    }

    /**
     * 三元替换 ，判断标准是 status == target
     *
     * @param status
     * @param target
     * @param o_true
     * @param o_false
     * @param <T>
     * @return
     */
    public static <T> T three_eq(Object status, Object target, T o_true, T o_false) {
        if (target != null) target = target.toString();
        if (status != null) status = status.toString();
        return Objects.equals(status, target) ? o_true : o_false;
    }


    /**
     * 三元替换 ，判断标准是 status == target
     *
     * @param status
     * @param target
     * @param o_true
     * @param o_false
     * @param <T>
     * @return
     */
    public static <T> T three_in(Object[] status, Object target, T o_true, T o_false) {
        if (status != null) {
            if (target != null) target = target.toString();
            for (Object s : status) {
                if (s != null) s = s.toString();
                return Objects.equals(s, target) ? o_true : o_false;
            }
        }
        return o_false;
    }


    public static String UUID() {
        return org.osgl.util.S.uuid().replace("-", "");
    }

    public static String replaceReg(String src, String reg, String with) {
        if (org.osgl.util.S.isBlank(src)) return src;
        return src.replaceAll(reg, with);
    }

    /**
     * 解析错误信息为前台统一格式
     *
     * @param errors
     * @return
     */
    public static String parseError(java.util.List<String> errors) {
        StringBuffer sb = new StringBuffer();
        sb.append("<ul style='text-align: left;width:auto;list-style-type:none'>");
        errors.forEach(item -> {
            sb.append("<li>");
            sb.append(item);
            sb.append("</li>");
        });
        sb.append("</ul>");
        return sb.toString();
    }


    /**
     * 返回以千分位分割,四舍五入的货币格式
     *
     * @param money      将要格式化的数字
     * @param prefix     货币前缀
     * @param split      用什么分割
     * @param num_digits 保留几位小数
     * @return
     */
    public static String formatMoney(BigDecimal money, String prefix, String split, int num_digits) {
        if (money == null) return null;
        if (split == null) split = ",";
        DecimalFormat fomater = new DecimalFormat();
        StringBuilder str = new StringBuilder("0");
        if (num_digits > 0)
            str.append(".");

        for (int i = 1; i <= num_digits; ++i)
            str.append("0");

        fomater.applyPattern(str.toString());
        String strNumber = fomater.format(money);
        String[] valuesa = strNumber.split("\\.");
        StringBuilder valueLast = new StringBuilder();
        int calcCount = 0, length = valuesa[0].length();

        for (int i = length - 1; i > -1; i--) {
            valueLast.insert(0, valuesa[0].charAt(i));
            calcCount++;
            if (calcCount % 3 == 0 && calcCount != length)
                valueLast.insert(0, split);
        }
        if (valuesa.length > 1) {
            valueLast.append(".");
            valueLast.append(valuesa[1]);
        }
        return prefix + valueLast.toString();
    }

    /**
     * 返回千分位分割,以￥开头，四舍五入、保留2位小数的货币格式
     *
     * @param money
     * @return
     */
    public static String formatMoney(BigDecimal money) {
        return formatMoney(money, "￥", ",", 2);
    }

    public static String formatMoneyObject(Object money,int len) {
        return formatMoney(new BigDecimal(money.toString()), "￥", ",", len);
    }


    /**
     * 返回千分位分割,以￥开头，四舍五入、保留0位小数的货币格式
     *
     * @param money
     * @return
     */
    public static String formatMoney(int money) {
        return formatMoney(new BigDecimal(money), "￥", ",", 2);
    }

    /**
     * 随机字符串(纯数字)
     *
     * @param size 位数
     * @return
     */
    public static String randomNumberString(int size) {
        int i = (int) ((Math.random() * 9 + 1) * Math.pow(10, (size - 1)));
        return String.valueOf(i);
    }

    public static int randomNumber(int size) {
        return (int) ((Math.random() * 9 + 1) * Math.pow(10, (size - 1)));
    }

    /**
     * 随机字符串
     *
     * @param length
     * @return
     */
    public static String randomString(int length) {
        Random random = new Random();
        StringBuilder ret = new StringBuilder();
        for (int i = 0; i < length; i++) {
            boolean isChar = (random.nextInt(2) % 2 == 0);// 输出字母还是数字
            if (isChar) { // 字符串
                int choice = random.nextInt(2) % 2 == 0 ? 65 : 97; // 取得大写字母还是小写字母
                ret.append((char) (choice + random.nextInt(26)));
            } else { // 数字
                ret.append(Integer.toString(random.nextInt(10)));
            }
        }
        return ret.toString();
    }

    /**
     * 订单号
     *
     * @param fix
     * @return
     */
    public static String buildOrderId(String fix) {
        String orderid = DateUtils.formatTimeNow("yyyyMMddHHmmss");
        return fix + orderid + String.valueOf(new Double((Math.random() * 8 + 1) * 1000000).intValue());
    }

    /**
     * 字符串拼接 例如 stringBuild("高级黑啊{0},太原热{1}",new String[]{"bay","book"});
     *
     * @param src
     * @param args
     * @return
     */
    public static String stringBuild(String src, String... args) {
        for (int i = 0, j = args.length; i < j; i++)
            src = src.replaceAll("\\{" + i + "\\}", args[i] + "");
        return src;
    }

    /**
     * 字符串拼接 例如 stringBuild("高级黑啊{name},太原热{age}",{"name":"cc","age":"20"});
     *
     * @param src
     * @param args
     * @return
     */
    public static String stringBuild(String src, Map args) {
        return stringBuild(src, args, false, false);
    }

    /**
     * 字符串拼接 例如 stringBuild("高级黑啊{name},太原热{age}",{"name":"cc","age":"20"});
     *
     * @param src
     * @param args
     * @param skipIfNotExist
     * @return
     */
    public static String stringBuild(String src, Map args, boolean skipIfNotExist) {
        return stringBuild(src, args, skipIfNotExist, false);
    }

    /**
     * 字符串拼接 例如 stringBuild("高级黑啊{name},太原热{age}",{"name":"cc","age":"20"});
     *
     * @param src
     * @param args
     * @param skipIfNotExist
     * @param no_r_n         是否屏蔽换行符
     * @return
     */
    public static String stringBuild(String src, Map args, boolean skipIfNotExist, boolean no_r_n) {
        return stringBuild(src, args, "{", "}", skipIfNotExist, no_r_n);
    }


    /**
     * 字符串拼接 例如 stringBuild("高级黑啊{name},太原热{age}",{"name":"cc","age":"20"});
     *
     * @param src
     * @param args
     * @param symbolStart
     * @param symbolEnd
     * @return
     */
    public static String stringBuild(String src, Map args, String symbolStart, String symbolEnd) {
        return stringBuild(src, args, symbolStart, symbolEnd, false, false);
    }

    /**
     * 字符串拼接 例如 stringBuild("高级黑啊{name},太原热{age}",{"name":"cc","age":"20"});
     *
     * @param src
     * @param args
     * @param symbolStart
     * @param symbolEnd
     * @param skipIfNotExist
     * @param no_r_n
     * @return
     */
    public static String stringBuild(String src, Map args, String symbolStart, String symbolEnd, boolean skipIfNotExist, boolean no_r_n) {
        if (org.osgl.util.S.isBlank(src)) return src;
        String def = new String();
        String beforeStart = "{}.[]^".indexOf(symbolStart) == -1 ? "" : "\\";
        String beforeEnd = "{}.[]^".indexOf(symbolEnd) == -1 ? "" : "\\";
        Pattern p = Pattern.compile(beforeStart + symbolStart + "([^" + beforeEnd + symbolEnd + "]+)" + beforeEnd + symbolEnd);
        Matcher m = p.matcher(src);
        StringBuffer buffer = new StringBuffer();
        while (m.find()) {
            String key = m.group(1);
            Object v = MapUtils.get(args, key, null);
            if (v == null) {
                if (skipIfNotExist) continue;
                else v = def;
            }
            if (no_r_n) {
                m.appendReplacement(buffer, v.toString().replaceAll("\r", "").replaceAll("\n", ""));
            } else {
                m.appendReplacement(buffer, v.toString());
            }
        }
        m.appendTail(buffer);
        return buffer.toString();
    }


    public static String appendZero(String src, int size) {
        StringBuilder sb = new StringBuilder(src);
        String zero = "0";
        for (int i = src.length(); i < size; i++) {
            sb.insert(0, zero);
        }
        return sb.length() > size ?  sb.substring(sb.length() - size) : sb.toString();
    }

    public static String appendZero(int src, int size) {
        StringBuilder sb = new StringBuilder(String.valueOf(src));
        String zero = "0";
        for (int i = sb.length(); i < size; i++) {
            sb.insert(0, zero);
        }
        return sb.toString();
    }

    public static String repeatWord(int size, String chat) {
        StringBuilder sb = new StringBuilder();
        for (int i = 0; i < size; i++) {
            sb.append(chat);
        }
        return sb.toString();
    }

    /**
     * 图片延迟加载、路径修复
     *
     * @param imgstr
     * @return
     */
    public static String qiniuImgDelay(String imgstr) {
        if (org.osgl.util.S.isBlank(imgstr)) {
            return "";
        }
        Pattern p = Pattern.compile("class=\"([^\"]+)\"", Pattern.CASE_INSENSITIVE);
        Matcher m = p.matcher(imgstr);
        StringBuffer buffer = new StringBuffer();
        while (m.find()) {
            m.appendReplacement(buffer, "");
        }
        m.appendTail(buffer);

        p = Pattern.compile("src=\"([^\"]+)\"", Pattern.CASE_INSENSITIVE);
        m = p.matcher(imgstr);
        buffer = new StringBuffer();
        while (m.find()) {
            if (!m.group(1).contains("http")) {
                m.appendReplacement(buffer, "style=\"max-width:100%;width:100%;height:auto\" src=\"" + AppConfig.base.basePath + m.group(1) + "\"");
            } else {
                m.appendReplacement(buffer, "style=\"max-width:100%;width:100%;height:auto\" src=\"" + m.group(1) + "\"");
            }
        }
        m.appendTail(buffer);
        return buffer.toString();
    }

    public static String regexGet(String regex, String value, int index) {
        try {
            Pattern p = Pattern.compile(regex);
            Matcher m = p.matcher(value);
            if (m.find()) {
                return m.group(index);
            }
        } catch (Exception e) {
        }
        return null;
    }

    /**
     * 文章内容路径处理
     * 将前端自动生成的../替换为/
     * @param article
     * @return
     */
    public static String rightDoArticle(String article){
        return article == null ? null : article.replaceAll("(\\.\\./|/)*file/","/file/");
    }

}
